/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package factorialcirculationadd;
import java.io.*;
import java.lang.*;
import java.math.*;

/**
 *
 * @author hhl
 */


public class FactorialCirculationAdd {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int n=0;
        String s="";
        System.out.println("本程序的功能：求1!+(1!+2!)+(1!+2!+3!)+...+(1!+2!+3!+...+n!)");
        System.out.println("下面，请输入n值：");
        try{
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            s=in.readLine();
        }
        catch(IOException e){}
        n=Integer.parseInt(s);
        FactorialSum(n);
    }

    public static void FactorialSum(int n){

        //只能用math里边的BigDecimal来存储数据
        //定义变量保存阶乘的和
        BigDecimal Allsum = new BigDecimal(0);

        for(int k=1;k<=n;k++){
            BigDecimal sum = new BigDecimal(0);
            for(int i =1; i<=k;i++){
                //定义变量保存阶乘的结果
                BigDecimal result = new BigDecimal(1);
                //循环求i的阶乘
                for (int j=1;j<=i;j++){
                    //把j的值转换成BigDecimal类型
                    BigDecimal  j_value = new BigDecimal(j);
                    //让result乘以i然后重新赋值给result
                    result = result.multiply(j_value);
                }
                //将阶乘的结果存入sum
                sum = sum.add(result);
            }
            Allsum = Allsum.add(sum);
        }
        //输出结果
        System.out.println("从1到"+n+"的阶乘循环和为"+Allsum);
    }
}
